package com.cakin.session;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @className: SessionDemo01
 * @description: 创建session
 * @date: 2020/6/9
 * @author: cakin
 */
public class SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 解决乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        // 获得session
        HttpSession session = req.getSession();
        Person person = new Person("xiaowang", "20");
        // 创建session
        session.setAttribute("person", person);
        // 浏览器输出
        PrintWriter out = resp.getWriter();
        if (session.isNew()) {
            out.write("session is new");
        } else {
            // 打印session
            out.write("session is" + session.getId());
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
